package com.huidz.calendar.activity;

import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.transition.Slide;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import com.google.gson.Gson;
import com.huidz.calendar.R;
import com.huidz.calendar.activityadapter.BeiWangLuAdapter;
import com.huidz.calendar.model.BWLModel;
import com.huidz.calendar.util.Apiutils;
import com.huidz.calendar.util.Url;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class BeiWangLuActivity extends AppCompatActivity implements View.OnClickListener {

    private ListView home_list;
    private List<Fragment> fraglist;
    private ImageView comeback;
    private ArrayList<BWLModel.data> new_list_view;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Slide slide = new Slide(Gravity.RIGHT);
        slide.setDuration(200L);//间歇时间
        getWindow().setEnterTransition(slide);
        setContentView(R.layout.bwl_listhead);
        inti();
    }

    public BeiWangLuAdapter myAdapter;

    /**
     * 初始化加载调用方法
     */
    public void inti() {
        comeback = findViewById(R.id.title_comeback);
        comeback.setOnClickListener(this);
        home_list = findViewById(R.id.bwl_list);
        new_list_view = new ArrayList<>();
        myAdapter = new BeiWangLuAdapter(new_list_view,
                BeiWangLuActivity.this);
        home_list.setAdapter(myAdapter);
        gettianqi();
        home_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                windows(BeiWangLuActivity.this,home_list,position,new_list_view.get(position).getId());
            }
        });
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_comeback:
                onBackPressed();
                break;
        }
    }

    public static long firstTime = 0;

    public void gettianqi() {
        OkHttpClient client = new OkHttpClient();
        //构造Request对象
        //采用建造者模式，链式调用指明进行Get请求,传入Get的请求地址
        Request request = new Request.Builder().get().url(Url.GETBWL + "?logintoken=" + Url.USER_TOKEN).build();
        Call call = client.newCall(request);
        //异步调用并设置回调函数
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, final Response response) {
                try {
                    final String responseStr;
                    responseStr = response.body().string();
                    Message message = new Message();
                    message.obj = responseStr;
                    gettq.sendMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public static BWLModel userms;
    public Handler gettq = new Handler() {
        public void handleMessage(Message msg) {
            String msgs = null;
            try {
                JSONObject success_Object = null;
                if (msg.obj != null) {
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    msgs = success_Object.getString("msg");
                    if (code.equals("1")) {
                        Gson gson = new Gson();
                        userms = gson.fromJson(msg.obj.toString(),
                                BWLModel.class);
                        new_list_view.addAll(userms.getData());
                        myAdapter.notifyDataSetChanged();
                    } else
                        Apiutils.SetToast(BeiWangLuActivity.this , msgs + "");
                }

            } catch (
                    Exception e) {
                e.printStackTrace();
            }
        }
    };

    private static PopupWindow popupWindows;

    public void windows(Context context, View v,int id,String listid) {
        View popupwindowviews = null;
        popupwindowviews = LayoutInflater.from(context).inflate(
                R.layout.popup_isdel, null);
        RelativeLayout dangqian = popupwindowviews.findViewById(R.id.dangqian);
        dangqian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent toaddjnrs = new Intent(BeiWangLuActivity.this, UpdateBWLActivity.class);
                toaddjnrs.putExtra("id", listid);
                startActivity(toaddjnrs, ActivityOptions.makeSceneTransitionAnimation(BeiWangLuActivity.this).toBundle());
                popupWindows.dismiss();
            }
        });
        RelativeLayout jieshu = popupwindowviews.findViewById(R.id.jieshu);
        jieshu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                okHttp_postFromParameters(new_list_view.get(id).getId());
                popupWindows.dismiss();
            }
        });
        popupWindows = new PopupWindow(popupwindowviews, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindows.setAnimationStyle(R.style.popwin_anim_style);
        popupWindows.setTouchable(true);
        popupWindows.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // TODO Auto-generated method stub
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
               getWindow().setAttributes(lp);
            }
        });
        popupWindows.setFocusable(true);
        popupWindows.setOutsideTouchable(true);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.4f;
        getWindow().setAttributes(lp);
        popupWindows.showAtLocation(v, Gravity.BOTTOM, 0, 0);
    }

    public void okHttp_postFromParameters(String postion) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    RequestBody formBody = new FormBody.Builder().add("remindid", postion+"")
                            .build();
                    Request request = new Request.Builder().url(Url.DELTX+"?logintoken="+Url.USER_TOKEN).post(formBody).build();
                    okhttp3.Response response = okHttpClient.newCall(request).execute();
                    String msg = response.body().string();
                    Message message = new Message();
                    message.obj = msg;
                    gethot.sendMessage(message);
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public Handler gethot = new Handler() {
        public void handleMessage(Message msg) {
            String msgs = null;
            try {
                JSONObject success_Object = null;
                if (msg.obj != null) {
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    msgs = success_Object.getString("msg");
                    if (code.equals("1")) {
                        Apiutils.SetToast(BeiWangLuActivity.this, msgs + "");
                        onBackPressed();
                    } else
                        Apiutils.SetToast(BeiWangLuActivity.this, msgs + "");
                }

            } catch (
                    Exception e) {
                e.printStackTrace();
            }
        }
    };
}
